import React, { Component } from 'react';
import { Toast } from 'antd-mobile';
import { hashHistory } from 'react-router';
import './UserAddress.less';
import SeperateLine from 'common/components/SeperateLine.js';
import Header from 'common/components/Header.js';

import * as common from 'common/common.js';
import * as userApi from 'common/api/UserApi.js';

/**
 * 地址管理组件
 * @param {addressId} 	路由参数:选中的地址ID
 * @param {addressList} 地址列表数据
 */
class UserAddress extends Component{
	
	constructor(props) {
	    super(props);
	    this.state = {
	    	addressId: this.props.params.addressId,
	    	addressList: []
	    }
	}
	
	componentDidMount(){
		Toast.loading("", common.TIPS_LOADING_DURATION);
		//获取用户地址列表
		userApi.userAddressList({
			userId: common.userId()
		}).then(result => {
			Toast.hide();
			if(result.code == common.SUCCESS){
				this.setState({
					addressList: result.data
				})
			}
		})
	}
	
	//选中地址
	selectAddress = (item) => {
		this.setState({
			addressId: item.id
		})
		common.goBack();
	}
	
	//编辑地址
	editAddress = (item) => {
		hashHistory.push({
			pathname: "/editAddress/"+item.id,
			state: item
		});
	}
	
	render(){
		const { addressList } = this.state;
		return(
			<div className="address">
				<Header title={"地址"}></Header>
				<SeperateLine lineHeight={"0.9rem"}></SeperateLine>
				{
					addressList.map((item, index)=>{
						var selectClassImg = item.addressId == this.state.addressId ? "assets/img/select.png" : "assets/img/unselect.png";
						return(
							<div key={index} className="list_item address_item">
								<div className="left" onClick={() => this.selectAddress(item)}>
									<img src={selectClassImg}/>
								</div>
								<div className="content" onClick={() => this.selectAddress(item)}>
									<div className="order_address_container">
										<div className="order_address">
											<div className="order_address_title">
												{item.receiverName} {item.phone}
											</div>
											<div className="order_address_info">
											  	{item.address}
											</div>
										</div>
									</div>
								</div>
								<div className="right" onClick={() => this.editAddress(item)}>
									<img src="assets/img/edit.png"/>
								</div>
							</div>
						)
					})
				}
			</div>
		)
	}
}

export default UserAddress;